/*******************************************************************************
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Jean Neveux - initial API and implementation
 *******************************************************************************/
package org.dynamo.database.ui.console;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.spi.ErrorCode;
import org.apache.log4j.spi.LoggingEvent;

/**
 * PluginLogAppender
 * This class is a custom Log4J appender that sends Log4J events to 
 * an Eclipse Console.
 */
public class LogAppender extends AppenderSkeleton {

	private ConsoleWriter writer;
	
	/**
	 * Log event happened.
	 * @param event LoggingEvent instance
	 */	
	public void append(LoggingEvent event) {
		
		if (this.layout == null) {
			this.errorHandler.error("Missing layout for appender " + 
			       this.name,null,ErrorCode.MISSING_LAYOUT); 
			return;
		}
		
		String text = this.layout.format(event);
		int level = ConsoleWriter.MSG_INFORMATION;
		if(event.getLevel().toInt() == Level.ERROR_INT)
			level  = ConsoleWriter.MSG_ERROR;
		else if(event.getLevel().toInt() == Level.WARN_INT)
			level = ConsoleWriter.MSG_WARNING;
				
		if(writer == null)
			writer = new ConsoleWriter();
		writer.print(text,level);

	}
	
	/**
	 * Closes this appender
	 */	
	public void close() {
		this.closed = true; 
	}
	
	/**
	 * Checks if this appender requires layout
	 * @return true if layout is required.
	 */	
	public boolean requiresLayout() {
		return true;
	}
}